package com.ld.security.auth;

import com.ld.security.UsernameExistException;
import com.ld.security.config.JwtService;
import com.ld.security.user.IUserRepository;
import com.ld.security.user.Role;
import com.ld.security.user.UserModel;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class AuthenticationService {

    private final IUserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtService jwtService;
    private final AuthenticationManager authenticationManager;

    public AuthenticationResponse register(RegisterRequest request) throws UsernameExistException {

        Optional<UserModel> model = userRepository.findByEmail(request.getEmail());
        if (model.isPresent()) {
            throw new UsernameExistException("账号已经存在");
        }

        var user = UserModel.builder()
                .email(request.getEmail())
                .name(request.getName())
                .credentials(passwordEncoder.encode(request.getCredentials()))
                .role(Role.USER)
                .build();
        userRepository.save(user);

        var token = jwtService.generateToken(user);
        return AuthenticationResponse.builder().token(token).build();
    }

    public AuthenticationResponse authenticate(AuthenticationRequest request) {
        authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        request.getEmail(),
                        request.getCredentials()
                )
        );

        var user = userRepository.findByEmail(request.getEmail())
                .orElseThrow();
        var token = jwtService.generateToken(user);

        return AuthenticationResponse.builder().token(token).build();
    }
}
